#ifndef TLPACKET_H
#define TLPACKET_H
#include <QByteArray>
#include <QObject>
#include <QString>
#include <QDataStream>
#include <QBuffer>

namespace Packets
{
    class TLPacket : QObject
    {
        Q_OBJECT

    public:
        struct pheader{
            quint8 cmd;
            quint16 size;
        };
        TLPacket(QByteArray &data);
        TLPacket(QString &data);
        TLPacket(pheader head, QByteArray &data);
        TLPacket(pheader head, QString &data);
        QString StDump(QByteArray &exdata);
        QString StDump();
        int GetCmd()        { return (int)_header.cmd; }
        int GetSize()       { return (int)_header.size; }
        pheader GetHead()   { return _header; }
        int GetSktDesc()    {return _socket; }
        void SetSktDesc(int SocketDescriptor)   { _socket = SocketDescriptor; }
        QByteArray* GetRaw(){ return &_data; }
        QDataStream* getStream(){ return &_stm; }

        void AddCompressData(QByteArray &data);
        void AddCompressData(QString &data);
        void AddCompressData(void* data, int size);

    private:
        void CreatePkt(QByteArray &data, pheader *head=NULL);
        void AddZdata(QByteArray &data);
        QByteArray _data;
        QBuffer _buffer;
        pheader _header;
        QDataStream _stm;
        int _socket;

        bool inline isHexDigit(QChar c) const
            {if (((c >= '0') && (c <= '9')) ||
                 ((c >= 'a') && (c <= 'f')) ||
                 ((c >= 'A') && (c <= 'F')))
                    return true; else return false; }
        bool inline isWhitespace(QChar c) const
            {if ((c == ' ') || (c == '\t')) return true; else return false; }
        bool inline isPrintable(char c) const
            {if ((c > 48) && (c < 126)) return true; else return false; }

        QString asciiDump() const
        {
            QString ascii;
            foreach (int c, _data)
            {
                if (isPrintable(c))
                    ascii.append(QChar(c));
                else
                    ascii.append(QChar('.'));
            }

            return ascii;
        }
    };
}
#endif // TLPACKET_H
